import * as React from "react";
import {Box, Paper, Table, TableCell, TableContainer, TableHead, TableRow} from "@mui/material";
import {useUserAttendance} from "../../hooks/useUserAttendance.ts";

interface Data {
    date: string;
    check_in_time: string;
    check_out_time: string;
    status: string;
}


const AllAttendance: React.FC = () => {

    const {userAttendance, data, error} = useUserAttendance();
    const [attendanceData, setAttendanceData] = React.useState<Data[]>([]);

    React.useEffect(() => {
        const fetchAttendance = async () => {
            await userAttendance();
            if (error) {
                console.log(error);
                return;
            }
            if (data) {
                const dataArray: Data[] = JSON.parse(data);
                const sortedData = dataArray.sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime());
                setAttendanceData(sortedData);
            }
        };

        fetchAttendance();
    }, [data]);


    return (
        <Box>
            <TableContainer component={Paper}>
                <Table sx={{minWidth: 350}}>
                    <TableHead>
                        {/*表头*/}
                        <TableRow>
                            <TableCell>日期</TableCell>
                            <TableCell>上班签到时间</TableCell>
                            <TableCell>下班签退时间</TableCell>
                            <TableCell>考勤情况</TableCell>
                        </TableRow>
                    </TableHead>

                    <tbody>
                    {attendanceData.map((row, index) => (
                        <TableRow key={index}>
                            {/*日期*/}
                            <TableCell>{row.date}</TableCell>
                            {/*上班签到时间*/}
                            <TableCell>{row.check_in_time}</TableCell>
                            {/*下班签到时间*/}
                            <TableCell>{row.check_out_time}</TableCell>
                            {/* 根据status值显示不同的文本 */}
                            <TableCell>
                                {row.status === 'late' ? '迟到' : row.status === 'leave early' ? '早退' : row.status === 'normal' ? '正常' : '迟到并且早退'}
                            </TableCell>
                        </TableRow>
                    ))}
                    </tbody>
                </Table>
            </TableContainer>
        </Box>
    );
};

export default AllAttendance;
